<template>
	<div class="rule-center">
		<div class="search">
			<el-card class="search-card">
				<el-form ref="formRef" :inline="true" :model="queryParam" class="demo-form-inline">
					<div class="form-ai">
						<el-form-item label="" prop="">
							<el-input style="width: 500px;" v-model="llmqueryInput" placeholder="请输入..." clearable />
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="llmunderstander">猜你想搜</el-button>
							<el-button type="primary" @click="audioStart">
								{{ isRecording ? '停止录音' : '开始录音' }}
							</el-button>
						</el-form-item>
					</div>
					<el-form-item label="簿记管理人" prop="bookManagerName" class="search-item">
						<el-input v-model="queryParam.bookManagerName" placeholder="请输入..." clearable />
					</el-form-item>
					<el-form-item label="主承销商" prop="leadManager" class="search-item">
						<el-input v-model="queryParam.leadManager" placeholder="请输入..." clearable />
					</el-form-item>
					<el-form-item label="注册通知" prop="regNoticeNumber" class="search-item">
						<el-input v-model="queryParam.regNoticeNumber" placeholder="请输入..." clearable />
					</el-form-item>
					<!-- <el-form-item label="债券角色" prop="debtRole" class="search-item">
						<el-select v-model="queryParam.debtRole" placeholder="请选择...">
							<el-option label="主承销商" value="zcxs" />
							<el-option label="团成员" value="tcy" />
							<el-option label="联主" value="lz" />
							<el-option label="分销商" value="fxs" />
						</el-select>
					</el-form-item> -->
					<el-form-item label="债券编码" prop="debtCode" class="search-item">
						<el-input v-model="queryParam.debtCode" placeholder="请输入..." clearable />
					</el-form-item>
					<!-- <el-form-item label="债券类型" prop="bondType" class="search-item">
						<el-select v-model="queryParam.bondType" placeholder="请选择...">
							<el-option label="CP" value="CP" />
							<el-option label="SCP" value="SCP" />
							<el-option label="PPNCP" value="PPNCP" />
							<el-option label="PPNMTN" value="PPNMTN" />
							<el-option label="ABN" value="ABN" />
							<el-option label="SDR" value="SDR" />
						</el-select>
					</el-form-item> -->
					<!-- <el-form-item label="是否参团" prop="offeredType" class="search-item">
						<el-input v-model="queryParam.offeredType" placeholder="请输入..." clearable />
					</el-form-item> -->
					<el-form-item style="margin-left: 10px;">
						<el-button type="primary" @click="onSubmit">搜索</el-button>
						<el-button @click="onReset(formRef)">重置</el-button>
					</el-form-item>
				</el-form>
			</el-card>
		</div>
		<div class="table">
			<div class="table-tool">
				<div class="tool-title">
					<p class="title-text">查询结果</p>
				</div>
				<div class="tool-btn">
					<!-- <el-button type="primary" :icon="Plus" @click="addRule">新建</el-button> -->
				</div>
			</div>
			<Table :data="tableData" :columns="columns" :height="tableHeight" :paginationConfig="paginationConfig"
				@page-change="handlePageChange" @size-change="handleSizeChange" />
		</div>
	</div>
	<EffectDialog ref="addDialogRef" />
</template>

<script lang="ts" setup>
import { computed, h, onMounted, reactive, ref } from 'vue'
import { Plus, } from '@element-plus/icons-vue'
import { Understand, Audio2Text, QueryPageList, DebtInfoDeleteById } from '@/api/ai'
import { ElButton, ElLink, ElPopconfirm, ElMessage, type FormInstance } from 'element-plus'
import Table from '@/components/Table/index.vue'
import EffectDialog from './addDialog.vue'

const formRef = ref<FormInstance>()

const addDialogRef = ref()
const queryParam = ref<any>({
	userInput: '',
	bookManagerName: '',
	leadManager: '',
	regNoticeNumber: '',
	debtRole: '',
	debtCode: '',
	bondType: '',
	offeredType: '',
})

const tableData = ref<any>([])

const paginationConfig = reactive({
	total: 0,
	currentPage: 1,
	pageSize: 10,
	paginationShow: true,
})

const columns = ref<any>([
	{
		prop: 'bondFullName',
		label: '债券信息',
		align: 'center',
	},
	// {
	// 	prop: 'debtProcess',
	// 	label: '债券过程',
	// 	align: 'center',
	// },
	{
		prop: 'debtAmount',
		label: '债券规模',
		align: 'center',
	},
	{
		prop: 'bookManagerName',
		label: '簿记管理人',
		align: 'center',
	},
	{
		prop: 'leadManager',
		label: '主承销商',
		align: 'center',
	},
	{
		prop: 'regNoticeNumber',
		label: '注册通知书',
		align: 'center',
	},
	// {
	// 	prop: 'debtRole',
	// 	label: '债券角色',
	// 	align: 'center',
	// },
	{
		prop: 'debtCode',
		label: '债券编码',
		align: 'center',
	},
	{
		prop: 'subBeginDate',
		label: '申购开始时间',
		align: 'center',
	},
	// {
	// 	prop: 'operate',
	// 	label: '操作',
	// 	align: 'center',
	// 	fixed: 'right',
	// 	width: 180,
	// 	render: (scope: any) => {
	// 		return [
	// 			h(
	// 				ElButton,
	// 				{
	// 					onClick: () => editClick(scope.row),
	// 					type: 'primary',
	// 					disabled: false,
	// 					size: 'small',
	// 					// icon: 'View',
	// 					round: false,
	// 					circle: false,
	// 					plain: false,
	// 					link: false,
	// 				},
	// 				{ default: () => '编辑' }
	// 			),
	// 			h(
	// 				ElPopconfirm,
	// 				{
	// 					title: '确定删除吗？',
	// 					onConfirm: () => removeClick(scope.row),
	// 				},
	// 				{
	// 					default: () => ['xxx'],
	// 					reference: () =>
	// 						h(
	// 							'span',
	// 							// props 传递
	// 							{
	// 								link: true,
	// 								type: 'danger',
	// 							},
	// 							// 内容配置
	// 							[
	// 								h(
	// 									ElButton,
	// 									{
	// 										// onClick: () => removeClick(scope.row),
	// 										type: 'danger',
	// 										disabled: false,
	// 										size: 'small',
	// 										style: 'margin-left: 12px; margin-right: 12px',
	// 										// icon: 'View',
	// 										round: false,
	// 										circle: false,
	// 										plain: false,
	// 										link: false,
	// 									},
	// 									{
	// 										default: () => '删除',
	// 									}
	// 								),
	// 							]
	// 						),
	// 				}
	// 			),
	// 		]
	// 	},
	// },
])


const tableHeight = computed(() => {
	const clientHeight = document.documentElement.clientHeight
	return clientHeight - 400
})

// 录音相关
const mediaRecorder = ref<any>(null)
const audioChunks = ref<any>()
const isRecording = ref(false)
const llmqueryInput = ref();

const handlePageChange = (val: any) => {
	paginationConfig.currentPage = val
	getTableData()
}

const handleSizeChange = (val: any) => {
	paginationConfig.pageSize = val
	getTableData()
}

let textContents: any = {};
const llmunderstander = () => {

	let userinput = ""
	let queryMatedata = ""
	if (llmqueryInput.value != undefined) {
		// 去除标点符号
		userinput = llmqueryInput.value.replace(/[，。！、？,.!?]/g, '');
	}
	if (textContents != null) {
		for (let txt in textContents) {
			queryMatedata = queryMatedata + txt + ":" + textContents[txt] + ";";
		}
	}
	const content = "<元数据>" + queryMatedata + "</元数据>" + "<输入>" + userinput + '</输入>"+"<指令>请将上述的 $输入 识别出 $元数据 的映射关系，将输入中中可能出现的内容，以其对应的英文名称作为json对象的key，并返回json对象，如果没有识别出来，就返回空对象,返回的结果必须是plant json，禁止出现markdown语法。在返回结果之前要仔细检查json中字段名称。</指令><响应格式>json</响应格式><样例>输入的簿记管理人是兴业银行，主承销商是中国光大银行，注册通知是中市协注[2015]CP100，债券编码是F041558055，那么返回的json是:{debtCode:F041558055,bookManagerName:兴业银行股份有限公司,leadManager:中国光大银行股份有限公司,regNoticeNumber:中市协注[2015]CP100号}</样例><严厉原则>除了规定的响应格式以外，不要出现任何其他的废话</严厉原则>';
	let params = {
		sysReqHead: {
			version: '',
			traceId: '',
			transSeq: '',
			serviceFramework: '',
			branchTxNo: '',
			nodeId: '',
			txType: '',
			method: '',
		},
		expandMap: {},
		reqHeader: {
			id: '',
		},
		reqBody: {
			content: content,
		},
	};
	Understand(params)
		.then((res) => {
			// let resdata = JSON.parse(res.respBody.resultMsg)
			// 内网deepseek格式不同
			let resData = JSON.parse(res.respBody.resultMsg).text[0]
			const startIndex = resData.indexOf('```json');
			if (startIndex !== -1) {
				const endIndex = resData.indexOf('```', startIndex + '```json'.length);
				if (endIndex !== -1) {
					const jsonContent = resData.slice(startIndex + '```json'.length, endIndex);
					let value = JSON.parse(jsonContent);

					// AI字段转换
					queryParam.value.leadManager = value.leadManager || value.leadUnderwriter || '';
					queryParam.value.bookManagerName = value.bookManagerName || value.bookManager || '';
					queryParam.value.regNoticeNumber = value.regNoticeNumber || value.registrationNotice || '';
					queryParam.value.debtCode = value.debtCode || value.bondCode || '';
				}
			}
			// for (let prop in resdata) {
			// 	if (queryParam.value.hasOwnProperty(prop)) {
			// 		queryParam.value[prop] = resdata[prop];
			// 	}
			// }

		})
}

const onSubmit = () => {
	getTableData()
}

const audioStart = async () => {

	if (!isRecording.value) {
		try {
			// 检查浏览器是否支持 mediaDevices
			if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
				ElMessage({
					message: '您的浏览器不支持访问麦克风，请使用最新版本的浏览器。',
					type: 'error',
				});
				return;
			}
			// 尝试获取麦克风权限
			const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
			console.log("%c Line:320 🍣 stream", "color:#93c0a4", stream);
			mediaRecorder.value = new MediaRecorder(stream);
			audioChunks.value = [];

			mediaRecorder.value.addEventListener('dataavailable', (event: any) => {
				if (event.data.size > 0) {
					audioChunks.value.push(event.data);
				}
			});

			mediaRecorder.value.addEventListener('stop', async () => {
				const audioBlob = new Blob(audioChunks.value, { type: 'audio/wav' });
				const formData = new FormData();
				formData.append('audio', audioBlob);
				try {
					Audio2Text(formData).then(res => {
						console.log("%c Line:350 🍪 res", "color:#33a5ff", res);
						let value = JSON.parse(res)
						console.log("%c Line:352 🌮 value", "color:#93c0a4", value);
						// queryParam.userInput = JSON.parse(JSON.stringify(res)).text[0].text.replace(/[，。！、？,.!?]/g, '')
						llmqueryInput.value = JSON.parse(res).text[0].text.replace(/[，。！、？,.!?]/g, '')
						// userinput = llmqueryInput.value.replace(/[，。！、？,.!?]/g, '');
					});
					// 这里替换为实际的语音识别API地址
				} catch (error: any) {
					console.log("%c Line:335 🍏 error", "color:#4fff4B", error);
					if (error.name === 'NotAllowedError') {
						ElMessage({
							message: '您拒绝了浏览器访问麦克风的权限，请在浏览器设置中重新授予权限。',
							type: 'error',
						});
					} else if (error.name === 'NotFoundError') {
						ElMessage({
							message: '未找到可用的麦克风设备，请检查设备连接。',
							type: 'error',
						});
					} else {
						ElMessage({
							message: `无法访问麦克风`,
							type: 'error',
						});
					}
				}
			});

			mediaRecorder.value.start();
			isRecording.value = true;
			ElMessage({
				message: '开始录音',
				type: 'success',
			})
		} catch (error) {
			ElMessage({
				message: '无法访问麦克风',
				type: 'error',
			})
		}
	} else {
		try {
			if (mediaRecorder.value && mediaRecorder.value.state !== 'inactive') {
				mediaRecorder.value.stop();
				mediaRecorder.value.stream.getTracks().forEach((track: any) => track.stop());
			}
			isRecording.value = false;
			ElMessage({
				message: '录音已停止',
				type: 'success',
			})
		} catch (error) {
			ElMessage({
				message: '停止录音失败',
				type: 'error',
			})
		}
	}
}

const onReset = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.resetFields()
	getTableData()
}

const addRule = () => {
	addDialogRef.value.showDialog(true)
	addDialogRef.value.setTitle('新增')
}


const editClick = (val: any) => {
	addDialogRef.value.showDialog(true)
	addDialogRef.value.setTitle('编辑')
}

const removeClick = (val: any) => {
	let params = {
		sysReqHead: {
			version: "",
			traceId: "",
			transSeq: "",
			serviceFramework: "",
			branchTxNo: "",
			nodeId: "",
			txType: "",
			method: ""
		},
		expandMap: {},
		reqHeader: {
			id: ""
		},
		reqBody: {
			id: "",
		}
	}
	DebtInfoDeleteById(params).then(res => {
		console.log("%c Line:344 🍧 res", "color:#ed9ec7", res);
		ElMessage({
			message: '删除成功',
			type: 'success',
		})
	})
}

const getTableData = () => {
	let params = {
		sysReqHead: {
			version: "",
			traceId: "",
			transSeq: "",
			serviceFramework: "",
			branchTxNo: "",
			nodeId: "",
			txType: "",
			method: ""
		},
		expandMap: {},
		reqHeader: {
			id: ""
		},
		reqBody: {
			// debtInfo: queryParam.value,
			debtInfo: {
				id: "",
				createBy: "",
				createTime: "",
				updateBy: "",
				updateTime: "",
				sysOrgCode: "",
				bondFullName: "",
				debtProcess: "",
				debtAmount: null,
				bookManagerName: queryParam.value.bookManagerName,
				leadManager: queryParam.value.leadManager,
				regNoticeNumber: queryParam.value.regNoticeNumber,
				subBeginDate: "",
				debtRole: queryParam.value.debtRole,
				debtCode: queryParam.value.debtCode,
				debtName: "",
				bondType: queryParam.value.bondType,
				subEndDate: "",
				consignPayEndDate: "",
				offeredType: queryParam.value.offeredType,
			},
			pageNo: 1,
			pageSize: 10
		}
	}
	QueryPageList(params).then(res => {
		tableData.value = res.respBody.listDebtInfo
		paginationConfig.total = res.respBody.total
	})
}

onMounted(() => {
	getTableData()
})
</script>

<style lang="css" scoped>
.rule-center {}

.search-card {
	margin-bottom: 20px;

}

.demo-form-inline .el-input {
	/* --el-input-width: 200px; */
}

.demo-form-inline .el-select {
	/* --el-select-width: 200px; */
}

.table-tool {
	margin-left: 10px;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.tool-title {
	box-sizing: border-box;
	position: relative;
	padding-left: 10px;
	font-size: 16px;
	line-height: 32px;
	color: #222222;
	font-weight: 500;

	&::before {
		position: absolute;
		display: block;
		content: '';
		left: 0;
		top: 7px;
		width: 4px;
		height: 16px;
		background-color: #3f8cf7;
	}
}

.tool-btn {
	margin-bottom: 20px;
}

.table {
	padding: 10px;
	background-color: #fff;
	position: relative;

}

.table-pagination {
	position: absolute;
	margin-top: 20px;
	right: 10px;
	bottom: 10px;
}

.search {}

.el-form-item {
	margin-bottom: 0px;
}

.form-ai {
	margin-bottom: 10px;
}

.search-item {
	width: 300px;
	margin: 8px 8px;
}
</style>
